package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.RedisKey;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: pandeng_zhu
 * @time: 2023/2/15 13:12
 */

//@CrossOrigin
@Slf4j
@Api(tags = "短信管理")
@RestController
@RequestMapping("/api/sms")
public class ApiController {


    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SmsService smsService;

    @GetMapping("/send/{mobile}")
    public R send(
            @ApiParam(value = "手机号", required = true)
            @PathVariable String mobile) {

        //手机号是否注册
        boolean result = coreUserInfoClient.checkMobile(mobile);
        System.out.println("result====" + result);
        Assert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);


        //MOBILE_NULL_ERROR(-202, "手机号不能为空"),
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //MOBILE_ERROR(-203, "手机号不正确"),
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        //生成验证码
        String smsCode = RandomStringUtils.randomNumeric(4);
        log.info("验证码：" + smsCode);
        //组装短信参数模板
        Map<String, Object> param = new HashMap<>();
        param.put("smsCode", smsCode);

        //发送短信
        smsService.sendSms(mobile, SmsProperties.TEMPLATE_CODE, smsCode, param);

        //验证码存入redis
        stringRedisTemplate.opsForValue().set(RedisKey.SRB_CORE_DICTLIST + mobile, smsCode, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
